package com.aaa.config;

/**
 * @Classname s
 * @Description TODO
 * @Date 2020/12/2 14:53
 * @Created by 腾飞
 * @describe        图片下载到本地
 */
import org.springframework.util.ClassUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
public class UploadImgUtils {


    public static String approvalFile(MultipartFile filecontent){
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName = RandomNumberUtils.getRandomString();
        //获取项目classes/static的地址
        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();

        // 扩展名
        String originalFileName = filecontent.getOriginalFilename();
        String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
        try {
            inputStream = filecontent.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
//            System.out.println(request.getSession().getServletContext().getRealPath("/"));
//            System.out.println(request.getSession().getServletContext().getRealPath(Constants.PROCESSPATH_JILIANG));
//            path = "D:\\IdeaProjects\\financial\\src\\main\\resources\\static\\img\\avatar\\";

            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(staticPath+"/img/avatar");
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath()+ "/" + File.separator + fileName +extension);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileName + extension;
    }

}